#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实时监控HTTP请求处理过程
"""

import requests
import threading
import time
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from backend.app import create_app
from flask import request, g
from functools import wraps

def create_monitored_app():
    """创建带监控的Flask应用"""
    app = create_app()
    
    # 添加请求监控
    @app.before_request
    def log_request_info():
        print(f"\n=== 请求开始 ===")
        print(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"方法: {request.method}")
        print(f"路径: {request.path}")
        print(f"完整URL: {request.url}")
        print(f"端点: {request.endpoint}")
        print(f"请求头: {dict(request.headers)}")
        print(f"用户代理: {request.headers.get('User-Agent', 'N/A')}")
        
        # 检查认证信息
        auth_header = request.headers.get('Authorization')
        print(f"Authorization头: {auth_header}")
        
        # 检查g对象
        print(f"g对象内容: {vars(g)}")
    
    @app.after_request
    def log_response_info(response):
        print(f"\n=== 响应结束 ===")
        print(f"状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")
        print(f"内容类型: {response.content_type}")
        print(f"内容长度: {response.content_length}")
        print(f"=== 请求完成 ===\n")
        return response
    
    return app

def test_concurrent_requests():
    """测试并发请求"""
    test_url = 'http://127.0.0.1:5000/api/netdisk/download/43/bb/43bb0dd030fe6beb70e92fdce9b1e560.mp4'
    
    def make_request(request_id):
        print(f"\n>>> 发起请求 {request_id} <<<")
        try:
            response = requests.get(test_url, timeout=10)
            print(f">>> 请求 {request_id} 完成: {response.status_code} <<<")
            if response.headers.get('content-type', '').startswith('application/json'):
                print(f">>> 请求 {request_id} JSON: {response.json()} <<<")
            else:
                print(f">>> 请求 {request_id} 文件大小: {len(response.content)} bytes <<<")
        except Exception as e:
            print(f">>> 请求 {request_id} 失败: {e} <<<")
    
    # 发起3个并发请求
    threads = []
    for i in range(3):
        thread = threading.Thread(target=make_request, args=(i+1,))
        threads.append(thread)
        thread.start()
        time.sleep(0.1)  # 稍微错开时间
    
    # 等待所有请求完成
    for thread in threads:
        thread.join()

if __name__ == '__main__':
    print("=== 启动监控服务器 ===")
    
    # 在新线程中启动监控服务器
    def run_monitored_server():
        app = create_monitored_app()
        app.run(host='127.0.0.1', port=5001, debug=False, use_reloader=False)
    
    server_thread = threading.Thread(target=run_monitored_server)
    server_thread.daemon = True
    server_thread.start()
    
    # 等待服务器启动
    print("等待服务器启动...")
    time.sleep(3)
    
    # 测试请求
    print("\n=== 开始测试请求 ===")
    test_concurrent_requests()
    
    print("\n=== 测试完成 ===")
    time.sleep(2)